//
//  TimerManager.swift
//

import UIKit

class TimerManager: NSObject {

    private var currentDate: Date?
    private var timer: DispatchSourceTimer?
    private var tempSecond: Int = 0
    private var didEnd: () -> Void = {}
    
    override init() {
        super.init()
        
        addNotification()
    }
    
    func schedule(second: Int, surplus: @escaping (Int) -> Void, end: @escaping () -> Void) {
        tempSecond = second
        didEnd = end
        let queue = DispatchQueue.global(qos: .default)
        let timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
        timer.schedule(wallDeadline: .now(), repeating: 1.0)
        timer.setEventHandler {
            if self.tempSecond <= 0 {
                timer.cancel()
                self.timer = nil
                end()
            } else {
                self.tempSecond -= 1
                surplus(self.tempSecond)
            }
        }
        timer.resume()
        self.timer = timer
    }
    
    func cancel() {
        if let t = timer {
            t.cancel()
            timer = nil
        }
    }
}

extension TimerManager {
    private func addNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(enterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    
    @objc private func enterBackground() {
        if let t = timer {
            t.suspend()
        }
        currentDate = Date()
    }
    
    @objc private func enterForeground() {
        guard let saveDate = currentDate, let t = timer else { return }
        let sec = Int(Date().timeIntervalSince(saveDate))
        if sec < tempSecond {
            tempSecond = tempSecond - sec
            t.resume()
        } else {
            didEnd()
            t.cancel()
            timer = nil
        }
    }
}
